package net.asfun.jvalog.domain;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

import javax.cache.Cache;
import javax.cache.CacheEntry;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import static net.asfun.jvalog.misc.Log.logger;

import com.google.appengine.api.memcache.stdimpl.GCacheFactory;

@SuppressWarnings("unchecked")
public class Gmcache {

	private static Cache gmcache;
	
	private CacheEntry centry;
	
	static {
		Map props = new HashMap();
		props.put(GCacheFactory.EXPIRATION_DELTA, 36000);
		try {
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			gmcache = cacheFactory.createCache(props);
		} catch (CacheException e) {
			logger.log(Level.WARNING, e.getMessage(), e);
		}
	}
	
	private Gmcache(){}

	public static void clear() {
		gmcache.clear();
	}

	public static boolean containsKey(Object key) {
		return gmcache.containsKey(key);
	}

	public static Object get(Object key) {
		return gmcache.get(key);
	}

	public static void put(Object key, Object value) {
		gmcache.put(key, value);
	}
	
	public static void remove(Object key) {
		gmcache.remove(key);
	}
	
	public static String stat() {
		return gmcache.getCacheStatistics().toString();
	}
	
	public static int size() {
		return gmcache.getCacheStatistics().getObjectCount();
	}
	
	public static Gmcache load(Object key){
		Gmcache cache = new Gmcache();
		cache.centry = gmcache.getCacheEntry(key);
		return cache;
	}
	
	public Object getKey() {
		return centry.getKey();
	}
	
	public Object getValue() {
		return centry.getValue();
	}
	
	public long getHits() {
		return centry.getHits();
	}
	
	public Date getUpdateDate() {
		return new Date(centry.getLastUpdateTime());
	}
	
	public Date getExpireDate() {
		return new Date(centry.getExpirationTime());
	}
	
	public Date getCreateDate() {
		return new Date(centry.getCreationTime());
	}
}
